<?php 

class Targets extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
	const TAG_COUNT = 5; 
	
	//At this point, target names have to be unique, even if they are defined by different users.
	//This must change
	function load_target_by_name($name)
	{
		$query = $this->db->from('targets')
						  ->where('name', $name)
						  ->get();
		$result_list = $query->result();
		if(count($result_list) > 0)
		{
			return $result_list[0];
		}
		else
		{
			return FALSE;
		}
	}
	function load_target_by_id($id)
	{
		$query = $this->db->from('targets')
						  ->where('idtargets', $id)
						  ->get();
		$result_list = $query->result();
		if(count($result_list) > 0)
		{
			return $result_list[0];
		}
		else
		{
			return FALSE;
		}
	}
	
  	function load_users_targets($user, $idcountry)
    {
    	  $query = $this->db->select("targets.*")
		  ->from('users_targets')
		  ->join('targets', 'users_targets.idtarget = targets.idtargets')
        ->where('iduser', $user->iduser)
		->order_by('priority')
        ->get();
        
        $result_list = $query->result();
        
        if( count($result_list) < Targets::TAG_COUNT)
        {
		   	  $country_result_list = $this->load_country_targets($idcountry);	
			  $i = 0;
			  while(count($result_list) < Targets::TAG_COUNT)
			  {
				$result_list[] = $country_result_list[$i];
				$i++;
			  }
        }
		return $result_list;
    }	   
     
  	function load_country_targets($idcountry)
    {
		if(isset($idcountry) || !empty($idcountry) )
		{
			$idcountry = 'xx';
		}
		$query = $this->db->select("targets.*")
		->from('country_targets')
		->join('targets', 'country_targets.idtarget = targets.idtargets')
		->where('idcountry', $idcountry)  
		->order_by('priority')
		->get();

		$result_list = $query->result();

        if( count($result_list) < Targets::TAG_COUNT)
        {
	    	  $query = $this->db->select("targets.*")
			  ->from('country_targets')
			  ->join('targets', 'country_targets.idtarget = targets.idtargets')
	          ->where('idcountry', "xx")  
			  ->order_by('priority')
	          ->get();
        	
	    	  $second_result_list = $query->result();	
			  $i = 0;
			  while(count($result_list) < Targets::TAG_COUNT)
			  {
				$result_list[] = $second_result_list[$i];
				$i++;
			  }
        }
		return $result_list;
    }	    
}